package com.study.servlet.admin;

import com.study.dao.AdminInfoDAO;
import com.study.dao.impl.AdminInfoDAOImpl;
import com.study.pojo.AdminInfo;
import com.study.util.MD5;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @PackgeName: com.study.servlet.admin
 * @ClassName: CountryAddServlet
 * @Author: 严志祥
 * Date: 2022-05-06 14:43
 * project name: web_project_medal
 * @Version:
 * @Description:
 */
@WebServlet("/admin/admin-add.let")
public class AdminAddServlet extends HttpServlet {
    private AdminInfoDAO dao = new AdminInfoDAOImpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.reset();
        resp.setContentType("application/json;charset=utf-8");
        try {
           AdminInfo a = new AdminInfo();
            String dateStr = req.getParameter("adminTime");
            Date date = new SimpleDateFormat("yyyy-MM-dd").parse(dateStr);

            a.setAdminName(req.getParameter("adminName"));
            //对密码进行MD5加密
            String adminPassword = req.getParameter("adminPassword");
            a.setAdminPassword(MD5.encode(adminPassword));
            a.setAdminTime(date);
            try {
                dao.insert(a);
                resp.getWriter().print("{\"ok\":true}");
            } catch (Exception ex) {
                throw new ServletException("管理员编号重复", ex);
            }
        }catch (Exception e){
            resp.getWriter().print("{\"ok\":false,\"msg\":\""+e.getMessage()+"\"}");
        }
        resp.flushBuffer();
    }
}
